<template>
  <div class="homework-list">
    <!-- 多作业显示 -->
    <div v-if="currentHomeworks.length > 0">
      <div
        v-for="(homework, index) in currentHomeworks"
        :key="homework.id"
        class="homework-item"
        :class="{ 'first-homework': index === 0 }"
      >
        <div class="homework-header">
          <div class="homework-title-section">
            <h3 class="homework-title">{{ homework.title }}</h3>
            <div class="homework-time">
              {{ formatTime(homework.startTime) }} - {{ formatTime(homework.endTime) }}
            </div>
          </div>
          <div v-if="isAdminLoggedIn" class="homework-actions">
            <el-button
              type="primary"
              size="small"
              @click="editHomework(homework)"
              :disabled="homework.status === 2"
            >
              <el-icon><Edit /></el-icon>
              {{ homework.status === 2 ? '查看' : '编辑' }}
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="manageDetails(homework)"
              :disabled="homework.status === 2"
            >
              <el-icon><List /></el-icon>
              管理作业项
            </el-button>
          </div>
        </div>

        <div class="homework-content">
          <!-- 开始按钮 -->
          <div v-if="homework.status === 0" class="start-section">
            <el-button
              type="primary"
              size="large"
              @click="startHomework(homework.id)"
              :loading="loading"
            >
              开始作业
            </el-button>
          </div>

          <!-- 作业明细列表 -->
          <div v-if="homework.status > 0" class="details-section">
            <div class="progress-info">
              <span class="progress-text">
                完成进度：{{ homework.completedItems }}/{{ homework.totalItems }}
                <span class="required-info">
                  (必须：{{ homework.requiredCompletedItems }}/{{ getTotalRequired(homeworkDetails) }})
                </span>
              </span>
              <span v-if="isRequiredCompleted(homework)" class="emoji">👍</span>
            </div>

            <div class="details-list">
              <div
                v-for="detail in getHomeworkDetails(homework.id)"
                :key="detail.id"
                class="detail-item"
                :class="{
                  completed: detail.isCompleted,
                  'required-item': detail.isRequired,
                  'optional-item': !detail.isRequired
                }"
                @click="handleItemClick(detail, $event)"
              >
                <el-checkbox
                  :model-value="detail.isCompleted"
                  :disabled="homework.status === 0"
                  @change="toggleComplete(detail)"
                  @click.stop
                />
                <div class="detail-info">
                  <span class="detail-content" :class="{ strikethrough: detail.isCompleted }">
                    {{ detail.content }}
                  </span>
                  <el-tag
                    v-if="!detail.isRequired"
                    type="info"
                    size="small"
                    class="type-tag"
                  >
                    非必须
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="no-homework">
      <el-empty description="当前时间段没有作业" />
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, List } from '@element-plus/icons-vue'
import { useHomeworkStore } from '@/store/homework'
import dayjs from 'dayjs'

const props = defineProps({
  currentHomeworks: {
    type: Array,
    default: () => []
  },
  homeworkDetails: {
    type: Array,
    default: () => []
  },
  isAdminLoggedIn: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['refresh', 'edit-homework', 'manage-details'])

const homeworkStore = useHomeworkStore()
const loading = ref(false)

// 根据作业ID获取对应的作业明细
const getHomeworkDetails = (homeworkId) => {
  return props.homeworkDetails.filter(detail => detail.homeworkId === homeworkId)
}

// 计算必须完成的项目总数
const getTotalRequired = (details) => {
  return details.filter(detail => detail.isRequired).length
}

// 判断必须作业是否完成
const isRequiredCompleted = (homework) => {
  const details = getHomeworkDetails(homework.id)
  const totalRequired = getTotalRequired(details)
  const completedRequired = details.filter(detail =>
    detail.isRequired && detail.isCompleted
  ).length
  return completedRequired === totalRequired && totalRequired > 0
}

const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).format('MM-DD HH:mm')
}

const startHomework = async (homeworkId) => {
  try {
    loading.value = true
    await homeworkStore.startHomework(homeworkId)
    ElMessage.success('作业已开始，加油！')
    emit('refresh')
  } catch (error) {
    console.error('开始作业失败:', error)
    ElMessage.error('开始作业失败，请重试')
  } finally {
    loading.value = false
  }
}

const handleItemClick = (detail, event) => {
  // 如果点击的是checkbox，让checkbox处理，不重复触发
  if (event.target.classList.contains('el-checkbox__input') ||
      event.target.classList.contains('el-checkbox__inner')) {
    return
  }
  toggleComplete(detail)
}

const toggleComplete = async (detail) => {
  if (detail.isCompleted) {
    ElMessage.info('你的' + detail.content + '作业已经完成了，真棒！')
    return
  }

  try {
    await ElMessageBox.confirm(
      `${detail.content} 作业确定已经完成了吗？`,
      '确认完成',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await homeworkStore.completeHomeworkDetail(detail.id)
    ElMessage.success('作业项已完成，继续加油！')
    emit('refresh')

    // 检查是否必须作业完成
    const homework = props.currentHomeworks.find(h =>
      getHomeworkDetails(h.id).some(d => d.id === detail.id)
    )

    if (homework && isRequiredCompleted(homework)) {
      setTimeout(() => {
        ElMessage({
          message: '太棒了！必须作业都完成了！🎉',
          type: 'success',
          duration: 3000
        })
      }, 1000)
    }
  } catch (error) {
    // ElMessageBox.confirm 在用户取消时会抛出 'cancel' 或一个包含 cancel 属性的错误
    // 检查是否为用户取消操作
    const isUserCancel = error === 'cancel' ||
                        error === 'close' ||
                        (error && error.cancel) ||
                        (error && error.message && error.message.includes('cancel'))

    if (!isUserCancel) {
      console.error('完成作业项失败:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 编辑作业
const editHomework = (homework) => {
  emit('edit-homework', homework)
}

// 管理作业明细
const manageDetails = (homework) => {
  emit('manage-details', homework)
}
</script>

<style scoped>
.homework-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.homework-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  background: #fafafa;
}

.homework-item.first-homework {
  border-color: #409eff;
  background: #f0f9ff;
}

.homework-item:last-child {
  margin-bottom: 0;
}

.homework-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.homework-title-section {
  flex: 1;
}

.homework-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.homework-time {
  font-size: 14px;
  color: #666;
}

.homework-actions {
  display: flex;
  gap: 8px;
  margin-left: 16px;
}

.homework-content {
  min-height: 200px;
}

.start-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px;
}

.details-section {
  min-height: 150px;
}

.progress-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: bold;
}

.progress-text {
  margin-right: 10px;
}

.required-info {
  color: #666;
  font-size: 14px;
  margin-left: 8px;
}

.emoji {
  font-size: 20px;
}

.details-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
}

.detail-item:hover {
  background: #e9ecef;
}

.detail-item.completed {
  background: #d4edda;
}

.detail-item.required-item {
  border-left: 4px solid #ff6b6b;
}

.detail-item.optional-item {
  border-left: 4px solid #4ecdc4;
}

.detail-info {
  margin-left: 12px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.detail-content {
  font-size: 16px;
  line-height: 1.5;
  flex: 1;
}

.type-tag {
  margin-left: 8px;
}

.strikethrough {
  text-decoration: line-through;
  color: #6c757d;
}

.no-homework {
  min-height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>